
const http = require('http');
const httpProxy = require('http-proxy');
const path = require('path');
const fs = require('fs');
const os = require('os');
class Nginx {
    constructor() {
        this.proxySrv = null;
        this.httpSrv = null;
    }

    async init() {
        this.proxySrv = httpProxy.createProxyServer();

        this.httpSrv = http.createServer((req, res) => {

            let urlParts = req.url.toString().split('/');
            log.debug("urlParts = ", urlParts);
            let clientIp = req.connection.remoteAddress.slice(7);

            switch (urlParts[1]) {
                case 'blog': {
                    //参数管理

                    this.forwardReq(req, res, `http://127.0.0.1:${instance.ini.Proxy.Blog}`);


                } break;


                default:
                    log.debug("检测到默认请求，发送给http://127.0.0.1:13000");
                    this.forwardReq(req, res, 'http://127.0.0.1:13000');

                    break;
            }


        });

        let promise = new Promise((resolve, reject) => {
            // if(os.platform() == 'win32') {
            //     //本地调试用
            //     this.httpSrv.listen(8080, () => {
            //         log.debug(`server listening at port ${8080}`);
            //         resolve();
            //     });
            // } else {
                this.httpSrv.listen(instance.ini.Nginx.port, () => {
                    log.debug(`server listening at port ${instance.ini.Nginx.port}`);
                    resolve();
                });
            // }

            
        });

        await promise;

    }

    forwardReq(req, res, target) {
        //tools.debug('---- forward to -----', target);
        this.proxySrv.web(req, res, { target: target }, (err) => {
            console.log('error happen ---', err);
        });
    }


    getReqBodyData(req) {
        return new Promise((resolve, reject) => {
            let data = '';
            req.on('data', function (chunk) {
                data += chunk
            });
            req.on('end', function () {
                var reqObj = JSON.parse(data);
                resolve(reqObj);
            });
            req.on('error', (err) => {
                reject(err);
            })
        });

    }

    writeResBody(res, data) {
        let statusCode = 200;

        res.writeHead(statusCode);
        res.end(JSON.stringify(data));
    }


}

module.exports = Nginx;